<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\paginator\driver\Bootstrap;
use addons\exam\controller\Question as QuestionApi;
use think\Cache;

use app\common\model\CourseQuestionCategory as CourseQuestionCategoryModel;
use app\common\model\CourseQuestion as CourseQuestionModel;
use app\common\model\courseContentLog as courseContentLogModel;
use app\common\services\CourseQuestionService;      //  课程题目
use app\common\services\QuestionLogService;         //  答题记录

use app\common\model\Config;
use redis\MyRedis;



/**
 * 
 */
class Question extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    /**
     * 获取课程章节下试题列表
     *
     * @return void
     */
    public function list(){

        $course_id = input('id/d',0);
        $cid       = input('cid/d',0);
        if(empty($course_id) && empty($cid)){
            return $this->error('参数错误');
        }

        $page = $this->getPerPage();
    
        $data['cid']       = $cid;
        $data['c.cate_id'] = $course_id;
        $data['page']      = $page['page'];
        $data['num']       = $page['num'];
        try{

            $redis_key = 'course_question_list:'.md5(serialize($data));
            // $list      = Cache::get($redis_key);
            // if($list && $this->__flush_cache === false && 1==2){
            // }else{

                $list = CourseQuestionService::list($data);
            //     Cache::set($redis_key,$list,$this->getTtl());
            // }
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }
        return $this->success('success',$list);
    }


    /**
     * 获取分类
     *
     * @return void
     */
    public function cateList(){

        $pid    = input('pid/d',0);
        $cid    = input('cid/d',0);

        $data['cid']    = $cid;
        $data['page']   = input('page/d',1);
        $data['limit']  = input('limit/d',10);

        $redis_key = 'course_cate_list:'.md5(serialize(input('')));
        $list      = Cache::get($redis_key);
        if($list && $this->__flush_cache === false){
        }else{

            if(!empty($pid)){
                $where['pid']   = ['=',$pid];
            }else{
                $where['pid']   = ['>',0];
            }

            $min = ($data['page'] - 1) * $data['limit'];
            $num = $data['limit'];
            $list = CourseQuestionCategoryModel::where('content_id',(9000+$data['cid']))
                ->where($where)
                ->field('id,name,pid')
                ->limit($min, $num)
                ->select();

            foreach($list as &$value){
                $value['type']     = CourseQuestionCategoryModel::where('id',$value['pid'])->value('name');
                $value['num']      = CourseQuestionModel::where('cate_id',$value['id'])->count();
                $value['done_num'] = courseContentLogModel::where(['course_id' => $value['id'],'user_id'=>$this->auth->id ])->count();
            }
            
            Cache::set($redis_key,$list,$this->getTtl());
        }
        return $this->success('success',$list);
    }




    /**
     * 雅思英语-阅读
     *
     * @return void
     */
    public function readList(){

        $id   = Config::where('name','ys_read')->value('value');

        $page_info  = $this->getPerPage();

        $cache_key  = 'readList:'.md5(serialize($id.'_'.$this->auth->id).serialize($page_info));
        $result     = Cache::get($cache_key);
        if($result && $this->__flush_cache === false){
        }else{
            $list = CourseQuestionService::readList($id,$page_info);
            Cache::set($cache_key,$result,$this->getTtl());
        }

        foreach($list['data'] as &$va){
            foreach ($va['sub'] as &$v) {
                #   是否已读
                // $v['read']  = MyRedis::getInstance()->sIsMember('ys_read:'.$this->auth->id,$v['id'])?1:0;
                $v['read'] = 0;
            }
        }

        //  已读数量
        $list['read_total'] = 0;
        return $this->success('success',$list);
    }


    /**
     * 提交答案
     *
     * @return void
     */
    public function submit(){
        
        $course_id = input('course_id/d',0);
        $type = input('emptyType/d',0);
        if( empty($course_id) ){
            return $this->error('参数错误');
        }

        //  提交答案
        $result = QuestionLogService::submit($this->auth->id,$course_id,$type);
        if($result['code'] == 0){
            return $this->error($result['msg']);
        }

        return $this->success('成功',['log_id'=>$result['log_id']]);
    }


    /**
     * 课程提交答案记录
     *
     * @return void
     */
    public function log(){
        
        $course_id = input('course_id/d',0);
        if( empty($course_id) ){
            return $this->error('参数错误');
        }

        // 获取答题记录
        $page_info  = $this->getPerPage();
        $result     = QuestionLogService::getLog($this->auth->id,$course_id,$page_info);
        $total      = count($result);
        $right_count= 0;
        if(isset(current($result)['right_count'])){
            $right_count = current($result)['right_count'] ?? 0;
        }
        $data = [
            "code"  => 1,
            "msg"   => "成功",
            "time"  => "1705319628",
            'data'  => $result,
            'total' => $total,
            'right_count' => $right_count
        ];
        return json_encode($data,JSON_UNESCAPED_UNICODE);
    }
    


    /**
     * 试题记录详情（用户答题回显）
     *
     * @return void
     */
    public function detail(){
        
        $course_id  = $this->request->post('course_id',0);
        $log_id     = $this->request->post('log_id/d',0);
        if( empty($log_id) ){
            return $this->error('参数错误');
        }

        $ids = CourseQuestionModel::where('cate_id',$course_id)->column('question_id');
        if(empty($ids)){
            $this->success('success',[]);
        }

        $result = QuestionLogService::detail($ids,$course_id,$this->auth->id,$log_id);
        return $this->success('success',$result);
    }
    

}
